<template>
	<view class="box-sms-button" @tap="onSendSMS">
		{{showBtnText}}
	</view>
</template>

<script setup>
	import {ref,computed} from "vue";
	import {RegMobile} from "@/utils/constant.js"
	import {showToast} from "@/utils/frameApi.js"
	import {sendSmsCode} from "@/http/apis/loginAPI.js"
	const props=defineProps({
		mobile:{
			type:String,
			default:""
		}
	})
	const emits=defineEmits(['setCacheCode'])
	let initTime=60;
	let time=ref(initTime);
	let sendTimes=ref(0)
	let sendTimer=ref(null);
	let sending=ref(false);
	let showBtnText= computed(()=>{
		if(sending.value){
			return `${time.value}s后重发`
		}
		if(sendTimes.value==0){
			return '发送验证码'
		}
		return "重新发送"
	})
	let tmpSend=false;
	const onSendSMS=async ()=>{
		if(sending.value||tmpSend){
			return;
		}
		tmpSend=true
		if(!RegMobile.test(props.mobile)){
			tmpSend=false;
			showToast({title:"请先输入正确的手机号"});
			return;
		}
		let sendResult=await sendSmsCode({user_phone:props.mobile}).catch(err=>{
			console.log(err,">>>")
			tmpSend=false;
		})
		if(!sendResult){
			tmpSend=false;
			return;
		}
		console.log(sendResult,">>>>>>>>",sendResult.msg_code)
		// emits('setCacheCode',sendResult.msg_code)
		tmpSend=false;
		sending.value=true;
		
		sendTimes.value+=1;
		time.value=initTime;
		countDownTime()
	}
	const countDownTime=()=>{
		let tmpTime=time.value;
		if(tmpTime<=0){
			clearTimeout(sendTimer);
			sending.value=false;
			sendTimer.value=null;
			return;
		}
		
		sendTimer.value=setTimeout(()=>{
			time.value=tmpTime-1;
			countDownTime()
		},1000)
	}
	
</script>

<style lang="less">
	.box-sms-button{
		position: relative;
		width: 156rpx;
		height: 56rpx;
		line-height: 56rpx;
		border: 1px solid #DEE0E1;
		border-radius: 28rpx;
		text-align: center;
		font-size: 24rpx;
		// font-family: PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
	}
</style>